<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item :label="$t('菜单_工艺路线')" prop="routeId">
        <el-select v-model="queryParams.routeId" :placeholder="$t('通用_请输入') + $t('菜单_工艺路线')" filterable size="small">
          <el-option v-for="item in routeOptions" :key="item.routeId" :label="item.routeName" :value="item.routeId">
            <span style="float: left">{{ item.routeName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.routeId }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="工艺路线名称" prop="routeName">
        <el-input v-model="queryParams.routeName" placeholder="请输入工艺路线名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item :label="$t('小包')"  prop="packName">
        <el-input v-model="queryParams.packName"  :placeholder="$t('通用_请输入') + $t('小包')"   clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="入包时间">
        <el-date-picker clearable v-model="queryParams.trackInTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择进站时间"></el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('通用_搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('通用_重置') }}</el-button>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" >{{ $t('通用_导出') }}</el-button>
        <!-- <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="openBatchSave = true">批次生成</el-button> -->
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="aResultList" size="mini" border>
      <el-table-column v-for="column in columns" :key="column.prop" :label="column.label" :prop="column.prop" :sortable="column.sortable"></el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <el-dialog title="批次生成" :visible.sync="openBatchSave" width="900px" append-to-body>
      <el-form label-width="100px" :inline="true" ref="form" :model="form" :rules="rules">
        <el-form-item label="工艺路线" prop="routeId">
          <el-select v-model="form.routeId" placeholder="请选择工艺路线" clearable filterable size="small">
            <el-option v-for="item in routeOptions" :key="item.routeId" :label="item.routeName" :value="item.routeId">
              <span style="float: left">{{ item.routeName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.routeId }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入包时间" prop="packTime">
          <el-date-picker v-model="daterangePackTime" style="width: 360px" value-format="yyyy/MM/dd HH:mm" type="datetimerange" range-separator="-" start-placeholder="最小值" end-placeholder="最大值" size="small"></el-date-picker>
        </el-form-item>
        <el-form-item label="小包数量" prop="packQty">
          <el-input v-model="form.packQty" type="number" placeholder="请输入小包数量" clearable size="small" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="submitBatchSaveForm" size="mini" v-loading.fullscreen.lock="fullscreenLoading">生 成</el-button>
          <el-button @click="cancelBatchSave" size="mini">取 消</el-button>
        </el-form-item>
        <el-divider content-position="center">小包明细</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" icon="el-icon-download" size="mini" @click="downloadBatchSaveTemplate">下载模板</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleClearBatchSave">清空</el-button>
          </el-col>
        </el-row>
        <div v-on:paste="handlePasteBatchSave">
          <el-table size="mini" :data="batchSaveList" :row-class-name="rowPumpInfoIndex" ref="HrEqpBase">
            <el-table-column label="序号" align="center" prop="index"/>
            <el-table-column label="小包号" prop="packName"></el-table-column>
            <el-table-column label="电池片数量" prop="packQty"></el-table-column>
            <el-table-column label="小包产出时间" prop="packTime1"></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteBatchSave(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <div slot="empty">暂无数据,可直接根据当前表头建Excel,ctrl+c复制数据,然后ctrl+v黏贴此处!</div>
          </el-table>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {
    retraceResultList,
    listAResult,
    getAResult,
    delAResult,
    addAResult,
    updateAResult,
    createResult,
    routeList
  } from "@/api/system/aResult";

  export default {
    name: "AResult",
    data() {
      return {
        // 遮罩层
        loading: true,
        fullscreenLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 追溯结果表格数据
        aResultList: [],
        batchSaveList: [],
        routeOptions: [],
        daterangePackTime: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openBatchSave: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          routeId: null,
          routeName: null,
          trackInTime: null,
          packName: null
        },
        // 表单参数
        form: {
          routeId: null,
          packQty: null,
          beginPackTime: null,
          endPackTime: null
        },
        // 表单校验
        rules: {
          routeId: [
            { required: true, message: "工艺路线不能为空", trigger: "change" }
          ],
        },
        columns: [],
      };
    },
    created() {
      routeList().then(response => {
        this.routeOptions = response.data;
        if (this.routeOptions && this.routeOptions.length > 0) {
          this.queryParams.routeId = this.routeOptions[0].routeId;
          this.getList();
        }
      });
    },
    methods: {
      getColumnsFromData(data) {
        const columns = [];
        if (data.length > 0) {
          const keys = Object.keys(data[0]); // 获取第一个对象的所有键名
          keys.forEach(key => {
            columns.push({
              label: key, // 列标题
              prop: key, // 绑定到数据的属性名
              sortable: false // 是否可排序，根据需要设置
            });
          });
        }
        return columns;
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('/system/aResult/export', {
          ...this.queryParams
        }, `user_${new Date().getTime()}.xlsx`)
      },

      /** 查询追溯结果列表 */
      getList() {
        this.loading = true;
        retraceResultList(this.queryParams).then(response => {
          this.aResultList = response.rows;
          this.columns = this.getColumnsFromData(this.aResultList);
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 下载模板按钮操作 */
      downloadBatchSaveTemplate() {
        this.download('system/aResult/downloadRetraceResultTemplate', {
          ...this.queryParams
        }, `批次生成维护模板_${new Date().getTime()}.xlsx`)
      },
      handlePasteBatchSave(event) {
        this.batchSaveList = [];
        var clipdata = event.clipboardData || window.clipboardData;
        let content = clipdata.getData("text/plain");
        var data = [];
        if (content.indexOf("\r\n") > -1) {
          data = content.split('\r\n');
        } else {
          data = content.split('\n');
        }
        if (data.length > 1000) {
          this.$modal.msgError("黏贴数据不能大于1000行");
          return false;
        }
        for (let text of data) {
          if (!text) continue;
          var obj = {
            packName: "",
            packQty: "",
            packTime1: ""
          };
          let arr = text.split('\t');
          let i = 0;
          for (var key in obj) {
            obj[key] = arr[i];
            i++;
          }
          this.batchSaveList.push(obj);
        }
      },
      cancelBatchSave() {
        this.openBatchSave = false;
        this.batchSaveList = [];
      },
      handleClearBatchSave() {
        this.batchSaveList = [];
      },
      rowPumpInfoIndex({row, rowIndex}) {
        row.index = rowIndex + 1;
      },
      handleDeleteBatchSave(row) {
        this.batchSaveList.splice(row.index - 1, 1);
      },
      validBatchSaveForm() {
        if (!this.batchSaveList) {
          this.$modal.msgError("上传数据不能为空！");
          return false;
        }
        if (null != this.form.packQty && '' != this.form.packQty && this.form.packQty <= 0) {
          this.$modal.msgError("主表小包数量不能小于等于0！");
          return false;
        }
        for (var i = 0; i < this.batchSaveList.length; i++) {
          if (!this.batchSaveList[i].packName) {
            this.$modal.msgError("第" + this.batchSaveList[i].index + "项小包号不能为空！");
            return false;
          }
          if (this.batchSaveList[i].packQty && this.batchSaveList[i].packQty <= 0) {
            this.$modal.msgError("第" + this.batchSaveList[i].index + "项小包数量不能小于等于0！");
            return false;
          }
          if (null != this.form.packQty && '' != this.form.packQty && this.batchSaveList[i].packQty) {
            this.$modal.msgError("主表已填写小包数量，明细表第" + this.batchSaveList[i].index + "项小包数量不能有值！");
            return false;
          }
          if ((null == this.form.packQty || '' == this.form.packQty) && !this.batchSaveList[i].packQty) {
            this.$modal.msgError("第" + this.batchSaveList[i].index + "项小包数量不能为空！");
            return false;
          }
          if (null != this.daterangePackTime && '' != this.daterangePackTime && this.batchSaveList[i].packTime1) {
            this.$modal.msgError("主表已选择小包产出时间范围，明细表第" + this.batchSaveList[i].index + "项小包产出时间不能有值！");
            return false;
          }
          if ((null == this.daterangePackTime || '' == this.daterangePackTime) && !this.batchSaveList[i].packTime1) {
            this.$modal.msgError("第" + this.batchSaveList[i].index + "项小包产出时间不能为空！");
            return false;
          }
        }
        return true;
      },
      submitBatchSaveForm() {
        this.fullscreenLoading = true;
        if (!this.validBatchSaveForm()) {
          this.fullscreenLoading = false;
          return;
        }
        this.form.beginPackTime = null;
        this.form.endPackTime = null;
        if (null != this.daterangePackTime && '' != this.daterangePackTime) {
          this.form.beginPackTime = this.daterangePackTime[0];
          this.form.endPackTime = this.daterangePackTime[1];
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            let data = {
              main: this.form,
              rows: this.batchSaveList
            };
            createResult(data).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.openBatchSave = false;
              this.batchSaveList = [];
              this.getList();
              this.fullscreenLoading = false;
            }).catch(error => {
              this.fullscreenLoading = false;
            });
          } else {
            this.fullscreenLoading = false;
          }
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/aResult/exportResult', {
          ...this.queryParams
        }, `追溯信息_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
